package com.xysoft.framework.mvc;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.LastModified;
import org.springframework.web.servlet.mvc.multiaction.MethodNameResolver;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

import com.xysoft.framework.event.ControllerAfterExecuteEvent;
import com.xysoft.framework.event.ControllerBeforeExecuteEvent;

public class BasicController extends AbstractController implements LastModified {

	private static final String METHOD_PREFIX = "do";

	public static final String LAST_MODIFIED_METHOD_SUFFIX = "LastModified";

	public static final String DEFAULT_COMMAND_NAME = "command";

	public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound";

	protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);

	private Object delegate;

	private MethodNameResolver methodNameResolver = new PrefixMethodNameResolver(METHOD_PREFIX);

	private Validator[] validators;

	private WebBindingInitializer webBindingInitializer;

	private final Map<String, Method> handlerMethodMap = new HashMap<String, Method>();

	private final Map<String, Method> lastModifiedMethodMap = new HashMap<String, Method>();

	private final Map<Class<?>, Method> exceptionHandlerMap = new HashMap<Class<?>, Method>();
	
	private HttpServletRequest request;
	private HttpServletResponse response;
	private String methodName;

	public HttpServletRequest getRequest() {
		return request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public String getMethodName() {
		return methodName;
	}

	public BasicController() {
		this.delegate = this;
		registerHandlerMethods(this.delegate);
	}

	public BasicController(Object delegate) {
		setDelegate(delegate);
	}

	public final void setDelegate(Object delegate) {
		Assert.notNull(delegate, "Delegate must not be null");
		this.delegate = delegate;
		registerHandlerMethods(this.delegate);
		if (this.handlerMethodMap.isEmpty()) {
			throw new IllegalStateException("No handler methods in class [" + this.delegate.getClass() + "]");
		}
	}

	public final void setMethodNameResolver(MethodNameResolver methodNameResolver) {
		this.methodNameResolver = methodNameResolver;
	}

	public final MethodNameResolver getMethodNameResolver() {
		return this.methodNameResolver;
	}

	public final void setValidators(Validator[] validators) {
		this.validators = validators;
	}

	public final Validator[] getValidators() {
		return this.validators;
	}

	public final void setWebBindingInitializer(WebBindingInitializer webBindingInitializer) {
		this.webBindingInitializer = webBindingInitializer;
	}

	public final WebBindingInitializer getWebBindingInitializer() {
		return this.webBindingInitializer;
	}

	private void registerHandlerMethods(Object delegate) {
		this.handlerMethodMap.clear();
		this.lastModifiedMethodMap.clear();
		this.exceptionHandlerMap.clear();

		Method[] methods = delegate.getClass().getMethods();
		for (Method method : methods) {
			if (isExceptionHandlerMethod(method)) {
				registerExceptionHandlerMethod(method);
			} else if (isHandlerMethod(method)) {
				registerHandlerMethod(method);
				registerLastModifiedMethodIfExists(delegate, method);
			}
		}
	}

	private boolean isHandlerMethod(Method method) {
		Class<?> returnType = method.getReturnType();
		if (ModelAndView.class.equals(returnType) || Map.class.equals(returnType) || String.class.equals(returnType)
				|| void.class.equals(returnType)) {
			return StringUtils.startsWith(method.getName(), METHOD_PREFIX);
		}
		return false;
	}

	private boolean isExceptionHandlerMethod(Method method) {
		return (isHandlerMethod(method) && method.getParameterTypes().length == 3 && Throwable.class
				.isAssignableFrom(method.getParameterTypes()[2]));
	}

	private void registerHandlerMethod(Method method) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found action method [" + method + "]");
		}
		this.handlerMethodMap.put(method.getName(), method);
	}

	private void registerLastModifiedMethodIfExists(Object delegate, Method method) {
		try {
			Method lastModifiedMethod = delegate.getClass().getMethod(method.getName() + LAST_MODIFIED_METHOD_SUFFIX,
					new Class[] { HttpServletRequest.class });
			Class<?> returnType = lastModifiedMethod.getReturnType();
			if (!(long.class.equals(returnType) || Long.class.equals(returnType))) {
				throw new IllegalStateException("last-modified method [" + lastModifiedMethod
						+ "] declares an invalid return type - needs to be 'long' or 'Long'");
			}
			this.lastModifiedMethodMap.put(method.getName(), lastModifiedMethod);
			if (logger.isDebugEnabled()) {
				logger.debug("Found last-modified method for handler method [" + method + "]");
			}
		} catch (NoSuchMethodException ex) {
		}
	}

	private void registerExceptionHandlerMethod(Method method) {
		this.exceptionHandlerMap.put(method.getParameterTypes()[2], method);
		if (logger.isDebugEnabled()) {
			logger.debug("Found exception handler method [" + method + "]");
		}
	}

	public long getLastModified(HttpServletRequest request) {
		try {
			String handlerMethodName = this.methodNameResolver.getHandlerMethodName(request);
			Method lastModifiedMethod = this.lastModifiedMethodMap.get(handlerMethodName);
			if (lastModifiedMethod != null) {
				try {
					Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate, request);
					return (wrappedLong != null ? wrappedLong : -1);
				} catch (Exception ex) {
					logger.error("Failed to invoke last-modified method", ex);
				}
			}
		} catch (NoSuchRequestHandlingMethodException ex) {
		}
		return -1L;
	}
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			this.request = request;
			this.response = response;
			this.methodName = this.methodNameResolver.getHandlerMethodName(request);
			return invokeNamedMethod(this.methodName, request, response);
		} catch (NoSuchRequestHandlingMethodException ex) {
			return handleNoSuchRequestHandlingMethod(ex, request, response);
		}
	}

	protected ModelAndView handleNoSuchRequestHandlingMethod(NoSuchRequestHandlingMethodException ex,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		pageNotFoundLogger.warn(ex.getMessage());
		response.sendError(HttpServletResponse.SC_NOT_FOUND);
		return null;
	}
	
	protected final ModelAndView invokeNamedMethod(String methodName, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Method method = this.handlerMethodMap.get(methodName);
		if (method == null) {
			throw new NoSuchRequestHandlingMethodException(methodName, getClass());
		}

		try {
			Class<?>[] paramTypes = method.getParameterTypes();
			List<Object> params = new ArrayList<Object>(2);
			
			if(paramTypes.length > 0) {
				Object command = newCommandObject(paramTypes[0]);
				params.add(command);
				
				if(paramTypes.length == 2 && paramTypes[1].equals(BindingResult.class)) {
					params.add(bind(request, command).getBindingResult());
				} else {
					bind(request, command).closeNoCatch();
				}
			}
			
			getApplicationContext().publishEvent(new ControllerBeforeExecuteEvent(this, this, methodName));

			Object returnValue = method.invoke(this.delegate, params.toArray(new Object[params.size()]));
			
			getApplicationContext().publishEvent(new ControllerAfterExecuteEvent(this, this, methodName));
			return massageReturnValueIfNecessary(returnValue);
		} catch (InvocationTargetException ex) {
			return handleException(request, response, ex.getTargetException());
		} catch (Exception ex) {
			return handleException(request, response, ex);
		}
	}

	@SuppressWarnings("unchecked")
	private ModelAndView massageReturnValueIfNecessary(Object returnValue) {
		if (returnValue instanceof ModelAndView) {
			return (ModelAndView) returnValue;
		} else if (returnValue instanceof Map) {
			return new ModelAndView().addAllObjects((Map<String, ?>) returnValue);
		} else if (returnValue instanceof String) {
			return new ModelAndView((String) returnValue);
		} else {
			return null;
		}
	}

	protected Object newCommandObject(Class<?> clazz) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("Creating new command of class [" + clazz.getName() + "]");
		}
		return BeanUtils.instantiateClass(clazz);
	}

	protected ServletRequestDataBinder bind(HttpServletRequest request, Object command) throws Exception {
		logger.debug("Binding request parameters onto MultiActionController command");
		ServletRequestDataBinder binder = createBinder(request, command);
		binder.bind(request);
		if (this.validators != null) {
			for (Validator validator : this.validators) {
				if (validator.supports(command.getClass())) {
					ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
				}
			}
		}
		return binder;
	}

	protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object command) throws Exception {
		ServletRequestDataBinder binder = new ServletRequestDataBinder(command, getCommandName(command));
		initBinder(request, binder);
		return binder;
	}

	protected String getCommandName(Object command) {
		return DEFAULT_COMMAND_NAME;
	}

	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		if (this.webBindingInitializer != null) {
			this.webBindingInitializer.initBinder(binder, new ServletWebRequest(request));
		}
	}

	/**
	 * Determine the exception handler method for the given exception.
	 * <p>
	 * Can return <code>null</code> if not found.
	 * 
	 * @return a handler for the given exception type, or <code>null</code>
	 * @param exception
	 *            the exception to handle
	 */
	protected Method getExceptionHandler(Throwable exception) {
		Class<?> exceptionClass = exception.getClass();
		if (logger.isDebugEnabled()) {
			logger.debug("Trying to find handler for exception class [" + exceptionClass.getName() + "]");
		}
		Method handler = this.exceptionHandlerMap.get(exceptionClass);
		while (handler == null && !exceptionClass.equals(Throwable.class)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Trying to find handler for exception superclass [" + exceptionClass.getName() + "]");
			}
			exceptionClass = exceptionClass.getSuperclass();
			handler = this.exceptionHandlerMap.get(exceptionClass);
		}
		return handler;
	}

	private ModelAndView handleException(HttpServletRequest request, HttpServletResponse response, Throwable ex)
			throws Exception {

		Method handler = getExceptionHandler(ex);
		if (handler != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Invoking exception handler [" + handler + "] for exception: " + ex);
			}
			try {
				Object returnValue = handler.invoke(this.delegate, request, response, ex);
				return massageReturnValueIfNecessary(returnValue);
			} catch (InvocationTargetException ex2) {
				logger.error("Original exception overridden by exception handling failure", ex);
				ReflectionUtils.rethrowException(ex2.getTargetException());
			} catch (Exception ex2) {
				logger.error("Failed to invoke exception handler method", ex2);
			}
		} else {
			ReflectionUtils.rethrowException(ex);
		}
		throw new IllegalStateException("Should never get here");
	}

}